<template>
  <div class="main-container">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-info">
        <h1>欢迎回来, {{ username }}</h1>
        <p class="today-date">{{ todayDate }}</p>
      </div>
      <el-button type="primary" @click="startStudy">开始学习</el-button>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日学习</span>
              <el-tag size="small" type="success"
                >{{ todayStudyHours }}小时</el-tag
              >
            </div>
          </template>
          <div class="progress-info">
            <el-progress
              type="circle"
              :percentage="Math.min((todayStudyHours / 4) * 100, 100)"
              :status="todayStudyHours >= 4 ? 'success' : ''"
            />
            <p>日目标: 4小时</p>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待办事项</span>
              <el-tag size="small" type="warning"
                >{{ pendingTodos.length }}项待完成</el-tag
              >
            </div>
          </template>
          <div class="todo-list">
            <div class="activity-list">
              <el-scrollbar>
                <template v-if="pendingTodos.length">
                  <div
                    v-for="todo in pendingTodos"
                    :key="todo.id"
                    class="todo-item"
                  >
                    <el-checkbox v-model="todo.completed">{{
                      todo.title
                    }}</el-checkbox>
                  </div>
                  <el-link type="primary" @click="goToTodo">查看全部</el-link>
                </template>
                <el-empty v-else description="暂无待办" />
              </el-scrollbar>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>最近动态</span>
              <el-tag size="small" type="info"
                >{{ recentActivities.length }}条</el-tag
              >
            </div>
          </template>
          <div class="activity-list">
            <el-scrollbar>
              <template v-if="recentActivities.length">
                <div
                  v-for="activity in recentActivities"
                  :key="activity.id"
                  class="activity-item"
                >
                  <div class="activity-content">
                    <!-- 活动标题 -->
                    <div class="activity-title">{{ activity.title }}</div>
                    <!-- 活动描述 -->
                    <div class="activity-description">
                      {{ activity.description }}
                    </div>
                    <!-- 活动时间和地点 -->
                    <div class="activity-meta">
                      <span class="activity-time">{{
                        formatTime(activity.time)
                      }}</span>
                      <span class="activity-location">{{
                        activity.location
                      }}</span>
                    </div>
                  </div>
                </div>
                <el-link type="primary" @click="goToWall">查看更多</el-link>
              </template>
              <el-empty v-else description="暂无动态" />
            </el-scrollbar>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 学习记录图表 -->
    <el-card class="chart-section" shadow="hover">
      <statistics></statistics>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { getStudyRecords, getTodos, getWallPosts } from "@/api";
import { ElMessage } from "element-plus";
import Statistics from "./Statistics.vue";

import { activityApi } from "@/api/activity";

const router = useRouter();
const username = ref(localStorage.getItem("username") || "同学");
const todayStudyHours = ref(0);
const pendingTodos = ref([]);
const recentActivities = ref([]);

// 获取今天的日期
const todayDate = computed(() => {
  const date = new Date();
  return date.toLocaleDateString("zh-CN", {
    year: "numeric",
    month: "long",
    day: "numeric",
    weekday: "long",
  });
});
// 格式化时间
const formatTime = (time) => {
  const date = new Date(time);
  return date.toLocaleString(); // 根据需求调整时间格式
};
const isToday = (date) => {
  const today = new Date();
  return (
    date.getDate() === today.getDate() &&
    date.getMonth() === today.getMonth() &&
    date.getFullYear() === today.getFullYear()
  );
};
function getClosestEvents(data, limit = 5) {
  if (!Array.isArray(data) || data.length === 0) {
    return [];
  }
  try {
    const now = new Date();
    const dataWithDiff = data.map((item) => {
      const eventDate = new Date(item.time);
      const diff = Math.abs(eventDate - now);
      return {
        ...item,
        diff,
      };
    });
    dataWithDiff.sort((a, b) => a.diff - b.diff);
    const result = dataWithDiff.slice(0, limit).map((item) => {
      const { diff, ...rest } = item;
      return rest;
    });

    return result;
  } catch (error) {
    console.error("Error processing data:", error);
    return [];
  }
}
// 获取数据
const fetchData = async () => {
  try {
    // 获取学习记录
    const res = await getStudyRecords();
    const records = res.results;
    let num = 0;
    records.forEach((i) => {
      if (isToday(new Date(i.created_at))) {
        num += i.duration;
      }
    });
    todayStudyHours.value = (num / 60 / 60).toFixed(2);
    // 获取待办事项
    const todos = await getTodos();
    pendingTodos.value = todos.filter((todo) => !todo.completed);
    // 获取动态
    const activitys = await activityApi.getActivities({ type: "created" });

    recentActivities.value = getClosestEvents(activitys);
  } catch (error) {
    console.error("获取数据失败:", error);
    ElMessage.error("获取数据失败");
  }
};

// 开始学习
const startStudy = () => {
  router.push("/study");
};

// 跳转到待办页面
const goToTodo = () => {
  router.push("/todo");
};

// 跳转到学习墙
const goToWall = () => {
  router.push("/wall");
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.main-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.welcome-info h1 {
  margin: 0;
  font-size: 24px;
  color: var(--el-text-color-primary);
}

.today-date {
  margin: 8px 0 0;
  color: var(--el-text-color-secondary);
}

.stats-section {
  margin-bottom: 24px;
  display: flex;
}

:deep(.el-card__body) {
  height: 100%;
}

/* 让 el-col 继承父级高度 */
.stats-section .el-col {
  display: flex;
  /* 关键：使卡片高度撑满 */
}

/* 强制卡片高度填满父级 */
.stats-section .el-card {
  width: 100%;
  /* 确保宽度不收缩 */
  display: flex;
  /* 启用 Flex 布局 */
  flex-direction: column;
  /* 内容垂直排列 */
}

/* 卡片内容区域自动滚动（可选） */
.stats-section .el-card__body {
  flex: 1;
  /* 填满剩余高度 */
  overflow-y: auto;
  /* 内容超出时显示滚动条 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  height: 100%;
}

.todo-list,
.activity-list {
  height: 200px;
}

.todo-item,
.activity-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.activity-content {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chart-section {
  margin-bottom: 24px;
}

.chart-container {
  height: 300px;
}

.activity-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}

.activity-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}

.activity-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.activity-meta {
  font-size: 12px;
  color: #909399;
}

.activity-time {
  margin-right: 8px;
}

.activity-location {
  font-style: italic;
}
</style>
